using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Comteck.Domain.Entities;

namespace Comteck.Ktt.Services.Infrastructure {
  public class KttUnitOfWork : IKttUnitOfWork {
    private readonly AppDbContext _context;
    private DbContextTransaction _transaction;
    private bool _disposed;

    public KttUnitOfWork(AppDbContext context) {
      _context = context;
    }

    public IKttRepository<TEntity, TKey> GetRepository<TEntity, TKey>() where TEntity : class, IEntity<TKey> {
      return new KttRepository<TEntity, TKey>(_context);
    }

    public async Task<int> SaveChangesAsync() {
      return await _context.SaveChangesAsync();
    }
    public void BeginTransaction() {
      _transaction = _context.Database.BeginTransaction();
    }

    public async Task CommitTransactionAsync() {
      if (_transaction != null) {
        await _context.SaveChangesAsync();
        _transaction.Commit();
        _transaction = null;
      }
    }

    public void RollbackTransaction() {
      if (_transaction != null) {
        _transaction.Rollback();
        _transaction = null;
      }
    }

    protected virtual void Dispose(bool disposing) {
      if (!_disposed) {
        if (disposing) {
          _context.Dispose();
        }
      }
      _disposed = true;
    }

    public void Dispose() {
      Dispose(true);
      GC.SuppressFinalize(this);
    }
  }
}
